﻿using System;
using System.Text.RegularExpressions;

namespace DataFiller.DataStorage.Interpreters
{
    public interface IInterpreter
    {
        /// <summary>
        /// if given string is a placeholder, function will return the deleget that could retrieve data for filling the place holder,
        /// if not, will return null
        /// </summary>
        /// <param name="placeHolder">a string place holder</param>
        /// <returns>function used for retrieve useful data from model</returns>
        Func<object, object> MatchCase(string placeHolder);
    }

    public abstract class InterpreterBase : IInterpreter
    {
        //the pattern
        protected string Exp;

        #region IInterpreter Members
        /// <summary>
        /// check to see whether the given string is a valid place holder
        /// </summary>
        /// <returns>if it's a valid place holder, return the delegate that can retrieve the corresponding data</returns>
        public Func<object, object> MatchCase(string placeHolder)
        {
            if (IsMatched(placeHolder))
                return RetrieveCorrespondingData;
            else
                return null;
        }
        /// <summary>
        /// check to see whether the given string is a valid place holder
        /// </summary>
        protected virtual bool IsMatched(string placeholder)
        {
            Regex r = new Regex(Exp, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match m = r.Match(placeholder);
            return m.Success;
        }
        /// <summary>
        /// used to retrieve the corresponding data from model
        /// </summary>
        protected abstract object RetrieveCorrespondingData(object model);

        #endregion
    }
}
